define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            var workOrderIndex=new Vue({
                el: "#workOrderIndex",
                data() {
                    return {
                        isAjax: true,
                        isAjaxtable: false,
                        tabsList: [{
                                name: 'all',
                                label: '全部'
                            },
                            {
                                name: '0',
                                label: '待处理'
                            },
                            {
                                name: '1',
                                label: '已处理'
                            }
                        ],
                        needDepartmentOptions: [{
                            value: 'all',
                            label: '全部'
                        }, {
                            value: 'finance',
                            label: '财务部'
                        }, {
                            value: 'invoice',
                            label: '发票部'
                        }, {
                            value: 'technical',
                            label: '技术部'
                        }, {
                            value: 'store',
                            label: '油站部'
                        }, {
                            value: 'customer',
                            label: '客服部'
                        }],
                        // form搜索-begin
                        searchForm: {
                            status: "all",
                            form_1_key: "user_phone",
                            form_1_value: "",
                            need_departments: "all",
                            visittime: [],
                        },
                        searchFormInit: {
                            status: "all",
                            form_1_key: "user_phone",
                            form_1_value: "",
                            need_departments: "all",
                            visittime: [],
                        },
                        searchOp: {
                            status: "=",
                            need_departments: "FINDIN",
                            visittime: 'range',
                            user_phone: "like",
                            order_sn: "like",
                        },
                        // form搜索-end

                        sort: 'createtime',

                        listData: [],
                        offset: 0,
                        limit: 10,
                        totalPage: 0,
                        currentPage: 1,
                    }
                },
                mounted() {
                    this.getListData();
                },
                methods: {

                    //导出 导出发货单
                    goExport(type = 'export') {
                        var that = this;
                        let filter = {}
                        let op = {}
                        for (key in that.searchForm) {
                            if (key == 'form_1_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_1_key] = that.searchForm[key];
                                }
                            } else if (key == 'visittime') {
                                if (that.searchForm[key]) {
                                    if (that.searchForm[key].length > 0) {
                                        filter[key] = that.searchForm[key].join(' - ');
                                    }
                                }
                            } else if (key == 'status' || key == 'need_departments') {
                                if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                    filter[key] = that.searchForm[key];
                                }
                            }
                        }
                        for (key in filter) {
                            op[key] = that.searchOp[key]
                        }
                        window.location.href = Config.moduleurl + "/oil/work_order/" + type + "?filter=" + JSON.stringify(filter) + "&op=" + JSON.stringify(op);
                    },

                    isLate(record) {
                        //修改为只要回复时间少于2小时就标红
                        if (record.status == '1') {
                            return false;
                        }
                        const visitTime = new Date(record.visittime * 1000);
                        const currentTime = new Date();
                        const responseDeadline = new Date(visitTime.getTime() + (record.huifu_hour-2) * 60 * 60 * 1000);
                        return currentTime > responseDeadline;
                    },
                    getDepartmentLabels(departmentValues) {
                        if (typeof departmentValues !== 'string' || departmentValues.trim() === '') {
                            return '无';
                        }
                        return departmentValues
                            .split(',')
                            .map(value => value.trim())
                            .map(value => {
                                const department = this.needDepartmentOptions.find(option => option.value === value);
                                return department ? department.label : '';
                            })
                            .filter(label => label !== '')
                            .join('|');
                    },
                    getListData() {
                        let that = this;
                        if (!that.isAjax) {
                            that.isAjaxtable = true;
                        }
                        let filter = {}
                        let op = {}
                        for (key in that.searchForm) {
                            if (key == 'form_1_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_1_key] = that.searchForm[key];
                                }
                            } else if (key == 'visittime') {
                                if (that.searchForm[key]) {
                                    if (that.searchForm[key].length > 0) {
                                        filter[key] = that.searchForm[key].join(' - ');
                                    }
                                }
                            } else if (key == 'status' || key == 'need_departments') {
                                if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                    filter[key] = that.searchForm[key];
                                }
                            }
                        }
                        for (key in filter) {
                            op[key] = that.searchOp[key]
                        }
                        Fast.api.ajax({
                            url: 'oil/work_order/index',
                            loading: false,
                            type: 'GET',
                            data: {
                                offset: that.offset,
                                limit: that.limit,
                                sort: that.sort,
                                order: 'desc',
                                filter: JSON.stringify(filter),
                                op: JSON.stringify(op)
                            },
                        }, function (ret, res) {
                            that.listData = res.data.rows;
                            that.totalPage = res.data.total;
                            that.isAjax = false;
                            that.isAjaxtable = false;
                            return false;
                        }, function (ret, res) {
                            that.isAjax = false;
                            that.isAjaxtable = false;
                            return false;
                        })
                    },
                    operation(opttype, id) {
                        let that = this;
                        switch (opttype) {
                            case 'create':
                                Fast.api.open("oil/work_order/add", "新建工单", {
                                    callback(data) {
                                        if (data.data) {
                                            that.getListData();
                                        }
                                    }
                                });
                                break;
                            case 'edit':
                                Fast.api.open("oil/work_order/edit?ids=" + id, "详情", {
                                    callback(data) {
                                        if (data.data) {
                                            that.getListData();
                                        }
                                    }
                                });
                                break;
                        }
                    },
                    screenEmpty() {
                        this.searchForm = JSON.parse(JSON.stringify(this.searchFormInit))
                    },
                    tabshandleClick(value) {
                        this.sort = 'createtime'
                        this.listData = [];
                        this.isAjaxtable = true;
                        this.offset = 0;
                        this.limit = 10;
                        this.totalPage = 0;
                        this.currentPage = 1;
                        this.getListData();
                    },
                    handleCurrentChange(val) {
                        this.currentPage = val;
                        this.offset = (val - 1) * this.limit;
                        this.getListData()
                    },
                    handleSizeChange(val) {
                        this.offset = 0
                        this.limit = val;
                        this.currentPage = 1;
                        this.getListData(this.activeStatus)
                    },
                    tableRowClassName({
                        rowIndex
                    }) {
                        if (rowIndex % 2 == 1) {
                            return 'bg-color';
                        }
                        return '';
                    },
                    tableCellClassName({
                        columnIndex
                    }) {
                        if (columnIndex == 1 || columnIndex == 2 || columnIndex == 7) {
                            return 'cell-left';
                        }
                        return '';
                    },
                },
            })
        },

        add: function () {
            Controller.detailInit('add');
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.detailInit('edit');
            Controller.api.bindevent();
        },
        detailInit: function (type) {
            var detailPage = new Vue({
                el: "#detailPage",
                data() {
                    return {
                        optType: type,
                        rulesAdd: {
                            user_phone: [{
                                required: true,
                                message: '请输入用户账号电话',
                                trigger: 'blur'
                            }],
                            order_sn: [{
                                required: true,
                                message: '请输入加油票订单号',
                                trigger: 'blur'
                            }],
                            store_name: [{
                                required: true,
                                message: '请输入加油站名',
                                trigger: 'change'
                            }],
                            huifu_hour: [{
                                required: true,
                                message: '请选择回复时间',
                                trigger: 'change'
                            }],
                        },
                        rulesEdit: {
                        },
                        formData:{},
                        formDataInit: {
                            user_phone:'',
                            user_name:'',
                            order_sn:'',
                            store_name:'',
                            oper_name:'',
                            work_type:'',
                            work_type_title:'',
                            visittime:'',
                            need_departments:'',
                            need_departments_arr:[],
                            huifu_hour:'2',
                            status:'0',
                            content:'',
                            re_oper_name:'',
                            re_work_type:'',
                            re_work_type_title:'',
                            re_visittime:'',
                        },
                        work_order_id: Config.row ? Config.row.id : null,
                        workTypeOptions: [{
                            value: 'mptel',
                            label: '小程序Tel'
                        }, {
                            value: 'mpol',
                            label: '小程序OL'
                        },{
                            value: 'apptel',
                            label: 'APPTel'
                        },{
                            value: 'appol',
                            label: 'APPOL'
                        },{
                            value: 'email',
                            label: 'E-mail'
                        },{
                            value: 'finance',
                            label: '财务部协助'
                        }, {
                            value: 'invoice',
                            label: '发票部协助'
                        }, {
                            value: 'technical',
                            label: '技术部协助'
                        }, {
                            value: 'store',
                            label: '油站部协助'
                        }, {
                            value: 'customer',
                            label: '客服部协助'
                        }],
                        needDepartmentOptions: [{
                            value: 'finance',
                            label: '财务部'
                        }, {
                            value: 'invoice',
                            label: '发票部'
                        }, {
                            value: 'technical',
                            label: '技术部'
                        }, {
                            value: 'store',
                            label: '油站部'
                        }, {
                            value: 'customer',
                            label: '客服部'
                        }],
                        huifuHourOptions: [{
                            value: '2',
                            label: '2小时'
                        }, {
                            value: '4',
                            label: '4小时'
                        }, {
                            value: '6',
                            label: '6小时'
                        }, {
                            value: '12',
                            label: '12小时'
                        }, {
                            value: '24',
                            label: '24小时'
                        }],
                        //回访记录相关
                        logList: [],
                        offset: 0,
                        limit: 10,
                        totalPage: 0,
                        currentPage: 1,
                    }
                },
                mounted() {
                    this.getLogListData();
                },
                created(){
                    this.initData();
                },
                methods: {
                    cheakOrderSn(){
                        let that = this;
                        Fast.api.ajax({
                            url: 'oil/work_order/cheakOrderSn',
                            loading: true,
                            type: 'POST',
                            data: {
                                order_sn: that.formData.order_sn,
                            },
                        }, function (ret, res) {
                            that.formData.store_name = res.data.store_name;
                            that.formData.user_phone = res.data.user_phone;
                            return false;
                        })
                    },
                    getLogListData() {
                        let that = this;
                        Fast.api.ajax({
                            url: 'oil/work_order_log/index',
                            loading: true,
                            type: 'GET',
                            data: {
                                work_order_id: that.work_order_id,
                                offset: that.offset,
                                limit: that.limit,
                            },
                        }, function (ret, res) {
                            that.logList = res.data.rows;
                            that.totalPage = res.data.total;
                            return false;
                        })
                        console.log(that.logList);
                    },
                    handleSizeChange(val) {
                        this.offset = 0
                        this.limit = val;
                        this.currentPage = 1;
                        this.getLogListData()
                    },
                    handleCurrentChange(val) {
                        this.currentPage = val;
                        this.offset = (val - 1) * this.limit;
                        this.getLogListData()
                    },
                    tableRowClassName({
                          rowIndex
                        }) {
                        if (rowIndex % 2 == 1) {
                            return 'bg-color';
                        }
                        return '';
                    },
                    initData() {
                        let that = this;
                        if (this.optType == 'add') {
                            this.formData = JSON.parse(JSON.stringify(this.formDataInit));
                        } else {
                            //赋值
                            this.formData = JSON.parse(JSON.stringify(this.formDataInit));
                            //数组赋值
                            for (key in this.formData) {
                                if (key == 'need_departments_arr') {
                                    if(Config.row[key.replace('_arr', '')].length>0){
                                        this.formData[key] = Config.row[key.replace('_arr', '')].split(',')
                                    }
                                } else if(key == 'visittime'&&Config.row[key]>0){
                                    this.formData['visittime'] = moment(Config.row[key] * 1000).format("YYYY-MM-DD HH:mm:ss");
                                }else {
                                    this.formData[key] = Config.row[key]||'';
                                }
                            }
                        }
                    },
                    formSubmit(formName) {
                        let that = this;
                        this.$refs[formName].validate((valid) => {
                            console.log(valid);
                            if (valid) {
                                console.log(that.formData);
                                let subData = JSON.parse(JSON.stringify(that.formData));

                                console.log(subData);
                                if (that.optType == 'add') {
                                    Fast.api.ajax({
                                        url: 'oil/work_order/add',
                                        loading: true,
                                        type: "POST",
                                        data: {
                                            data: JSON.stringify(subData)
                                        }
                                    }, function (ret, res) {
                                        Fast.api.close({
                                            data: true
                                        })
                                    })
                                } else if(that.optType == 'edit') {
                                    Fast.api.ajax({
                                        url: 'oil/work_order/edit?ids=' + that.work_order_id,
                                        loading: true,
                                        type: "POST",
                                        data: {
                                            data: JSON.stringify(subData)
                                        }
                                    }, function (ret, res) {
                                        Fast.api.close({
                                            data: true
                                        })
                                    })
                                }
                            } else {
                                return false;
                            }
                        });
                    },
                    changeNeedDepartment(val){
                        this.formData.need_departments = val.join(',')
                    },
                    changeWorkType(val){
                        const workType = this.workTypeOptions.find(option => option.value === val);
                        this.formData.work_type_title = workType?.label;
                    },
                    changeReWorkType(val){
                        const reWorkType = this.workTypeOptions.find(option => option.value === val);
                        this.formData.re_work_type_title = reWorkType?.label;
                    },
                },
            })
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
